package jwt_util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"mine-info-server/utils/consts"
	"time"
)

//自定义 Claims
type CustomClaims struct {
	UserId string
	jwt.StandardClaims
}

//解析 token
func ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(consts.SecretKey), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

// GenerateToken 生成token
func GenerateToken() (string, error) {
	//生成 token
	maxAge := 60 * 60 * 24 * 3
	customClaims := &CustomClaims{
		UserId: consts.USERID, //用户 id
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间，必须设置
			Issuer:    "jerry",                                                    // 非必须，也可以填充用户名，
		},
	}
	//采用 HMAC SHA256 加密算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	tokenString, err := token.SignedString([]byte(consts.SecretKey))
	if err != nil {
		return "", err
	}
	return tokenString, nil
}
